__author__ = 'janos'

import Image
import ImageDraw
import ImageFont
import os

class DrawTextImage(object):
    def __init__(self, width, height, font = "Arial", font_size = 30, background_color = (0.2,0.2,0.2), font_directory="C:\\windows\\fonts\\"):
        self.font_directory = font_directory
        self.width = width
        self.height = height
        self.font_size = font_size

        self.background_color = self._convert_decimal_color_to_int(background_color)

        self.image = Image.new("RGBA",(self.width, self.height),color=self.background_color)
        self.font = font
        self.draw_image = ImageDraw.Draw(self.image)

        self.font_obj = self._font_obj(font_size)

    def _convert_decimal_color_to_int(self, color):
        if color.__class__ == tuple:
            r,g,b = (255*color[0],255*color[1],255*color[2])
        else:
            r,g,b = 255 * color
        return (int(r),int(g),int(b))


    def _font_obj(self,font_size):
        return ImageFont.truetype(os.path.join(self.font_directory,self.font + ".ttf"), size = font_size)


    def get_size(self,text,font_size = None):
        if not(font_size):
            font_size = self.font_size
        return self.draw_image.textsize(text, font=self.font_obj)


    def write_text(self,text,v_align = "center", h_align = "center", font_size = None, font_color = (0,0,0)):

        if not(font_size):
            font_size = self.font_size
        x_delta,y_delta = self.get_size(text,font_size)


        if v_align == "center" and h_align == "center":
            x = int(x_delta / 2.0)
            y = int(y_delta / 2.0)

            x_draw = int((self.width / 2.0) - x)
            y_draw = int((self.height / 2.0)  - y)

        else:
            x_draw = 0
            y_draw = 0

        self.draw_image.text((x_draw,y_draw),text,font=self.font_obj,fill = font_color)

    def write_file(self, file_name, file_type="PNG"):
        self.image.save(file_name, file_type)














